const kitchenService = require('../../services/kitchenService');
const discoverService = require('../../services/discoverService');
const app = getApp()
const db = wx.cloud.database()
const _ = db.command

Page({
  /**
   * 页面的初始数据
   */
  data: {
    dishId: '',
    kitchenId: '',
    dish: null,
    kitchen: null,
    userInfo: null,
    isFavorite: false,
    isLiked: false,
    isEditMode: false,
    showShareModal: false,
    loading: true,
    comments: [],
    commentText: '',
    showCommentInput: false,
    submitting: false,
    commentsLoading: false,
    hasMoreComments: true,
    currentCommentPage: 0,
    commentPageSize: 10,
    entryFrom: 'default'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { kitchenId, dishId, isEdit, from } = options;
    const entryFrom = from === 'discover' ? 'discover' : 'default';
    const isEditMode = isEdit === 'true' && entryFrom === 'default';
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'theme-green';
    this.setData({ theme });
    console.log('Dish Detail onLoad:', { options, entryFrom, isEditMode });

    this.setData({
      dishId,
      kitchenId,
      entryFrom,
      isEditMode,
      loading: true
    });

    if (entryFrom === 'discover') {
      if (dishId) {
        this.loadDataForDiscover(dishId, kitchenId);
        this.setData({ isEditMode: false });
      } else {
        console.error("Discover entry requires dishId");
        wx.showToast({ title: '参数错误', icon: 'none' });
        this.setData({ loading: false });
      }
    } else {
      if (isEditMode) {
        if (dishId && kitchenId) {
          this.loadDataForKitchen(kitchenId, dishId, true);
        } else if (kitchenId) {
          this.setData({
            loading: false,
            dish: {
              name: '', price: '', description: '', image: '', tags: [], calories: '',
              difficulty: '简单', cookingTime: '', ingredients: [], steps: [], tips: [],
              nutrition: { protein: '', fat: '', carbs: '', fiber: '' }
            }
          });
        } else {
          console.error("Edit mode requires kitchenId");
          wx.showToast({ title: '参数错误', icon: 'none' });
          this.setData({ loading: false });
        }
      } else if (dishId && kitchenId) {
        this.loadDataForKitchen(kitchenId, dishId, false);
      } else {
        console.error("Default entry requires dishId and kitchenId (or edit mode)");
        wx.showToast({ title: '参数错误', icon: 'none' });
        this.setData({ loading: false });
      }
    }
  },
  
  /**
   * 加载数据
   */
  loadData(dishId, kitchenId) {
    console.log('开始加载菜品数据:', { dishId, kitchenId });
    this.setData({ loading: true });

    db.collection('mydishes').doc(dishId).get().then(res => {
      const dish = res.data;
      console.log('加载菜品结果:', dish);

      if (!dish) {
        console.error('菜品不存在:', dishId);
        wx.showToast({ title: '菜品不存在', icon: 'none' });
        this.setData({ loading: false });
        setTimeout(() => wx.navigateBack(), 1500);
        return Promise.reject('Dish not found');
      }
      
      this.setData({ dish });

      const promises = [
        db.collection('myUser').where({ _id: dish.userId }).get().then(userRes => {
          const userInfo = userRes.data[0] || {};
          console.log('加载用户信息结果:', userInfo);
          this.setData({ 'dish.userInfo': userInfo });
        }).catch(err => {
          console.error('加载用户信息失败', err); 
          this.setData({ 'dish.userInfo': {} }); 
        }),
      ];

      if (kitchenId) {
        promises.push(
          kitchenService.getKitchenById(kitchenId).then(kitchen => {
            console.log('加载厨房信息结果:', kitchen);
            this.setData({ kitchen });
          }).catch(err => {
            console.error('加载厨房信息失败 (kitchenId: ' + kitchenId + ')', err);
            this.setData({ kitchen: null });
          })
        );
      }

      const favorites = wx.getStorageSync('myfavorites') || [];
      const isFavorite = favorites.some(fav => fav.dishId === dish._id && (!kitchenId || fav.kitchenId === kitchenId));
      console.log('检查收藏状态结果:', isFavorite);
      this.setData({ isFavorite });

      this.checkLikeStatus(dishId);

      this.loadComments(dishId);

      return Promise.all(promises);

    }).then(() => {
      console.log('菜品、用户、厨房信息加载完成');
      this.setData({ loading: false });
    }).catch(err => {
      if (err !== 'Dish not found') {
          console.error('加载菜品详情流程失败', err);
          wx.showToast({ title: '加载失败', icon: 'none' });
      }
      this.setData({ loading: false });
    });
  },
  
  /**
   * 检查点赞状态
   */
  checkLikeStatus: function(dishId) {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      console.log('检查点赞状态：用户未登录');
      this.setData({ isLiked: false });
      return;
    }
    
    db.collection('Like').where({
      userId: userInfo._id,
      dishId: dishId
    }).count().then(res => {
      console.log('检查点赞状态结果:', res.total > 0);
      this.setData({
        isLiked: res.total > 0
      });
    }).catch(err => {
      console.error('检查点赞状态失败:', err);
      this.setData({ isLiked: false });
    });
  },

  /**
   * 切换收藏状态
   */
  toggleFavorite() {
    const { dish, kitchenId, isFavorite } = this.data;
    if (!dish || !dish._id) return;

    const dishId = dish._id;
    const newFavoriteStatus = !isFavorite;
    const userInfo = wx.getStorageSync('userInfo');

    if (!userInfo || !userInfo._id) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    const dbAction = newFavoriteStatus 
        ? db.collection('myfavorites').add({ 
            data: { 
              userId: userInfo._id, 
              dishId: dishId, 
              kitchenId: kitchenId || null,
              collectionTime: new Date() 
            } 
          })
        : db.collection('myfavorites').where({ 
            userId: userInfo._id, 
            dishId: dishId,
          }).remove();

    const deletePromise = newFavoriteStatus ? Promise.resolve() : db.collection('myfavorites').where({ 
            userId: userInfo._id, 
            dishId: dishId,
          }).remove();

    dbAction.then(() => {
      this.setData({ isFavorite: newFavoriteStatus });
      
      let localFavorites = wx.getStorageSync('myfavorites') || [];
      if (newFavoriteStatus) {
          localFavorites.push({ userId: userInfo._id, dishId: dishId, kitchenId: kitchenId || null, _id: 'temp-' + Date.now() });
      } else {
          localFavorites = localFavorites.filter(fav => !(fav.userId === userInfo._id && fav.dishId === dishId));
      }
      wx.setStorageSync('myfavorites', localFavorites);

      wx.showToast({
        title: newFavoriteStatus ? '已收藏' : '已取消收藏',
        icon: 'success'
      });
    }).catch(err => {
      console.error('更新收藏状态失败：', err);
      wx.showToast({ title: '操作失败', icon: 'error' });
    });
  },

  /**
   * 点赞菜品
   */
  likeDish: function() {
    const { dishId, isLiked } = this.data;
    if (!dishId) return;
    
    const newLikeStatus = !isLiked;
    const currentLikeCount = this.data.dish.likeCount || 0;
    const newLikeCount = newLikeStatus ? currentLikeCount + 1 : Math.max(0, currentLikeCount - 1);

    this.setData({
      isLiked: newLikeStatus,
      'dish.likeCount': newLikeCount
    });

    discoverService.likeDish(dishId).then(liked => {
      if (liked === null) {
        console.error('点赞/取消点赞失败 (service)');
        this.setData({
          isLiked: isLiked,
          'dish.likeCount': currentLikeCount
        });
        wx.showToast({ title: '操作失败', icon: 'none' });
      } else if (liked !== newLikeStatus) {
         console.warn('点赞状态与预期不符，以服务器为准');
         this.setData({ isLiked: liked });
      } else {
         console.log('点赞/取消点赞成功');
          wx.showToast({
            title: liked ? '已点赞' : '已取消点赞',
            icon: 'success'
          });
      }
    }).catch(err => {
        console.error('点赞/取消点赞异常:', err);
         this.setData({
          isLiked: isLiked,
          'dish.likeCount': currentLikeCount
        });
        wx.showToast({ title: '操作失败', icon: 'none' });
    });
  },

  /**
   * 添加到购物车
   */
  addToCart() {
    const { kitchenId, dish } = this.data;
    if (!dish) {
       wx.showToast({title: '菜品信息加载中', icon: 'none'});
       return;
    }
    
    let cart = wx.getStorageSync('cart') || [];
    
    const existingItem = cart.find(item => item.dishId === dish._id && item.kitchenId === kitchenId);
    
    if (existingItem) {
      existingItem.quantity += 1;
    } else {
      cart.push({
        kitchenId: kitchenId,
        dishId: dish._id,
        name: dish.name,
        image: dish.image,
        price: dish.price || 0,
        quantity: 1,
        timestamp: new Date().getTime()
      });
    }
    
    wx.setStorageSync('cart', cart);
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
  },
  
  /**
   * 返回
   */
  navigateBack() {
    wx.navigateBack();
  },
  
  /**
   * 显示分享选项
   */
  showShareOptions() {
    this.setData({
      showShareModal: true
    });
  },

  /**
   * 隐藏分享选项
   */
  hideShareOptions() {
    this.setData({
      showShareModal: false
    });
  },

  /**
   * 分享到发现页
   */
  shareToDiscovery() {
    const { kitchenId, dish } = this.data;
    if (!dish) return;
    
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      this.hideShareOptions();
      return;
    }

    db.collection('Share').where({
      userId: userInfo._id,
      dishId: dish._id
    }).count().then(res => {
      if (res.total > 0) {
        wx.showToast({
          title: '您已分享过此菜品',
          icon: 'none'
        });
        this.hideShareOptions();
        return;
      }

      db.collection('Share').add({
        data: {
          userId: userInfo._id,
          userName: userInfo.nickname,
          userAvatar: userInfo.avatarUrl,
          dishId: dish._id,
          kitchenId: kitchenId || null,
          shareTime: new Date(),
          dishName: dish.name,
          dishImage: dish.image,
          likeCount: 0,
          commentCount: 0
        }
      }).then(() => {
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
        this.hideShareOptions();
      }).catch(err => {
        console.error('分享到发现页失败:', err);
        wx.showToast({
          title: '分享失败',
          icon: 'error'
        });
        this.hideShareOptions();
      });
    }).catch(err => {
        console.error('检查分享记录失败:', err);
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
        this.hideShareOptions();
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const { dish, dishId, kitchenId } = this.data;
    
    let path = `/pages/dish-detail/dish-detail?dishId=${dishId}`;
    if (this.data.entryFrom === 'discover') {
        path += '&from=discover';
    }
    if (kitchenId) {
      path += `&kitchenId=${kitchenId}`;
    }
    
    return {
      title: dish ? `来看看「${dish.name}」这道菜` : '分享菜品',
      path: path,
      imageUrl: dish && dish.image ? dish.image : ''
    };
  },

  /**
   * 显示评论输入框
   */
  showCommentInput: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      wx.showToast({ title: '请先登录后评论', icon: 'none' });
      return;
    }
    this.setData({ showCommentInput: true });
  },
  
  /**
   * 隐藏评论输入框
   */
  hideCommentInput: function() {
    this.setData({ 
      showCommentInput: false,
      commentText: ''
    });
  },
  
  /**
   * 输入评论内容
   */
  onCommentInput: function(e) {
    this.setData({ commentText: e.detail.value });
  },
  
  /**
   * 提交评论
   */
  submitComment: function() {
    const { dishId, commentText, kitchenId } = this.data;
    
    if (!commentText.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' });
      return;
    }
    
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    this.setData({ submitting: true });
    
    discoverService.addComment(dishId, commentText, kitchenId).then(comment => {
      if (comment) {
        const currentUserInfo = wx.getStorageSync('userInfo') || {};
        comment.userInfo = {
          nickName: currentUserInfo.nickName || '匿名用户',
          avatarUrl: currentUserInfo.avatarUrl || '/imgs/default-avatar.png'
        };

        const newComments = [comment, ...this.data.comments];
        
        this.setData({
          comments: newComments,
          commentText: '',
          showCommentInput: false,
          submitting: false,
          'dish.commentCount': (this.data.dish.commentCount || 0) + 1
        });
        
        wx.showToast({ title: '评论成功', icon: 'success' });
      } else {
        this.setData({ submitting: false });
        wx.showToast({ title: '评论失败', icon: 'none' });
      }
    }).catch(err => {
      console.error('提交评论失败:', err);
      this.setData({ submitting: false });
      wx.showToast({ title: '评论失败，请重试', icon: 'none' });
    });
  },
  
  /**
   * 加载评论
   */
  loadComments: function(dishId = this.data.dishId, loadMore = false) {
    if (!dishId) return;
    if (this.data.commentsLoading) return;
    if (loadMore && !this.data.hasMoreComments) return;

    const { commentPageSize } = this.data;
    const currentPage = loadMore ? this.data.currentCommentPage : 0;

    this.setData({ commentsLoading: true });
    
    discoverService.getComments(dishId, commentPageSize, currentPage * commentPageSize)
      .then(comments => {
        console.log(`加载评论结果 (page: ${currentPage}):`, comments);
        const commentsWithUserInfo = comments.map(c => ({
          ...c,
          userInfo: c.userInfo || { nickName: '用户', avatarUrl: '/imgs/default-avatar.png' } 
        }));

        const newComments = currentPage === 0 
          ? commentsWithUserInfo
          : [...this.data.comments, ...commentsWithUserInfo];
        
        this.setData({
          comments: newComments,
          hasMoreComments: comments.length === commentPageSize,
          currentCommentPage: currentPage + 1,
          commentsLoading: false
        });
      })
      .catch(err => {
        console.error('加载评论失败', err);
        this.setData({ commentsLoading: false });
      });
  },

  /**
   * 页面上拉触底事件的处理函数 - 加载更多评论
   */
  onReachBottom: function () {
    console.log('页面触底，尝试加载更多评论');
    this.loadComments(this.data.dishId, true);
  },

  /**
   * 输入处理
   */
  onInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    if (field.includes('.')) {
      const keys = field.split('.');
      this.setData({
        [`dish.${keys[0]}.${keys[1]}`]: value
      });
    } else {
      this.setData({
        [`dish.${field}`]: value
      });
    }
  },

  /**
   * 设置难度
   */
  setDifficulty(e) {
    this.setData({
      'dish.difficulty': e.detail.value
    });
  },

  /**
   * 保存菜品
   */
  saveDish() {
    const { dish, kitchenId, isEditMode } = this.data;
    console.warn("SaveDish function needs review for combined logic");
    wx.showToast({title: '保存功能待适配', icon: 'none'});
  },

  // =============================================
  // == Discover 模式数据加载与方法 ==
  // =============================================

  /**
   * 加载数据 (Discover 入口)
   */
  loadDataForDiscover(dishId, kitchenId) {
    console.log('加载数据 (Discover):', { dishId, kitchenId });
    this.setData({ loading: true });

    // 1. 获取菜品基础信息 (直接从 mydishes 获取)
    db.collection('mydishes').doc(dishId).get().then(res => {
      const dish = res.data;
      console.log('加载菜品 (Discover):', dish);

      if (!dish) {
        // ... 错误处理 ...
        console.error('菜品不存在 (Discover):', dishId);
        wx.showToast({ title: '菜品不存在', icon: 'none' });
        this.setData({ loading: false });
        setTimeout(() => wx.navigateBack(), 1500);
        return Promise.reject('Dish not found');
      }

      this.setData({ dish });

      // 并行加载：用户信息, Like状态, Favorite状态, 评论
      const promises = [
        // 2. 获取用户信息
        db.collection('myUser').where({ _id: dish.userId }).get().then(userRes => {
          const userInfo = userRes.data[0] || {};
          console.log('加载用户信息 (Discover):', userInfo);
          this.setData({ 'dish.userInfo': userInfo }); // 存在 dish 里方便 WXML 使用
        }).catch(err => { console.error('加载用户信息失败 (Discover)', err); this.setData({ 'dish.userInfo': {} }); }),

        // 3. 检查点赞状态 (Like 集合)
        this.checkLikeStatus(dishId),

        // 4. 检查收藏状态 (myfavorites 集合)
        this.checkFavoriteStatus(dishId, kitchenId), // 注意 kitchenId 可能为空

        // 5. 加载评论 (Comment 集合)
        this.loadComments(dishId) // 初始加载第一页评论
      ];
      
      // 6. 如果 discover 模式也传入了 kitchenId，可以选择性加载厨房信息
      if (kitchenId) {
          promises.push(
              kitchenService.getKitchenById(kitchenId).then(kitchen => {
                  console.log('加载厨房信息 (可能来自 Discover):', kitchen);
                  this.setData({ kitchen }); // 共享 kitchen 数据
              }).catch(err => {
                  console.error('加载厨房信息失败 (kitchenId: ' + kitchenId + ')', err);
                  this.setData({ kitchen: null });
              })
          );
      }


      return Promise.all(promises);

    }).then(() => {
      console.log('Discover 模式数据加载完成');
      this.setData({ loading: false });
    }).catch(err => {
      if (err !== 'Dish not found') {
        console.error('加载 Discover 菜品详情失败', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
      }
      this.setData({ loading: false });
    });
  },

  /**
   * 检查收藏状态 (Discover, 使用 myfavorites)
   */
  checkFavoriteStatus: function (dishId, kitchenId) {
     return new Promise((resolve) => { // 收藏状态检查失败不应阻塞页面
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo._id) {
            this.setData({ isFavorite: false });
            resolve();
            return;
        }
        // 从 myfavorites 集合中检查
        db.collection('myfavorites').where({
            userId: userInfo._id,
            dishId: dishId,
            // kitchenId: kitchenId || _.or(_.isNull(), _.isUndefined()) // 精确匹配 kitchenId，如果需要的话
        }).count().then(res => {
             console.log('检查收藏状态结果 (Discover):', res.total > 0);
             this.setData({ isFavorite: res.total > 0 });
             resolve();
        }).catch(err => {
            console.error('检查收藏状态失败 (Discover):', err);
            this.setData({ isFavorite: false }); // 失败则认为未收藏
            resolve(); // 保证 Promise 完成
        });
     });
  },

   /**
   * 切换收藏状态 (Discover, 操作 myfavorites)
   */
  toggleFavoriteForDiscover() {
    const { dish, kitchenId, isFavorite } = this.data; // 使用 discover 的 isFavorite
    if (!dish || !dish._id) return;

    const dishId = dish._id;
    const newFavoriteStatus = !isFavorite;
    const userInfo = wx.getStorageSync('userInfo');

    if (!userInfo || !userInfo._id) { /* 登录提示 */ wx.showToast({ title: '请先登录', icon: 'none' }); return; }

    const favData = { userId: userInfo._id, dishId: dishId, collectionTime: new Date() };
    if (kitchenId) favData.kitchenId = kitchenId; // 只有存在时才添加

    const dbAction = newFavoriteStatus
      ? db.collection('myfavorites').add({ data: favData })
      : db.collection('myfavorites').where({ userId: userInfo._id, dishId: dishId }).remove(); // 简化删除条件

    dbAction.then(res => {
      // 如果是添加操作，可以获取 _id 更新本地缓存，但非必需
      this.setData({ isFavorite: newFavoriteStatus });

      // --- 更新本地缓存 'myfavorites' (可选但推荐) ---
      let localFavorites = wx.getStorageSync('myfavorites') || [];
      if (newFavoriteStatus) {
          // 查找是否已存在（防止重复添加 - 尽管不太可能发生）
          if (!localFavorites.some(fav => fav.userId === userInfo._id && fav.dishId === dishId)) {
             favData._id = res._id || ('temp-' + Date.now()); // 使用数据库返回的 id 或临时 id
             localFavorites.push(favData);
          }
      } else {
          localFavorites = localFavorites.filter(fav => !(fav.userId === userInfo._id && fav.dishId === dishId));
      }
      wx.setStorageSync('myfavorites', localFavorites);
      // --- 本地缓存更新结束 ---

      wx.showToast({ title: newFavoriteStatus ? '已收藏' : '已取消收藏', icon: 'success' });
    }).catch(err => {
      console.error('更新收藏状态失败 (Discover)：', err);
      wx.showToast({ title: '操作失败', icon: 'error' });
    });
  },

  /**
   * 显示评论输入框 (Discover)
   */
  showCommentInput: function () {
    if (this.data.entryFrom !== 'discover') return;
    // ... (登录检查，设置 showCommentInput - 逻辑保持不变) ...
     const userInfo = wx.getStorageSync('userInfo');
     if (!userInfo || !userInfo._id) {
       wx.showToast({ title: '请先登录后评论', icon: 'none' });
       return;
     }
     this.setData({ showCommentInput: true });
  },

  /**
   * 隐藏评论输入框 (Discover)
   */
  hideCommentInput: function () {
    // ... (设置 showCommentInput, 清空 commentText - 逻辑保持不变) ...
     this.setData({ showCommentInput: false, commentText: '' });
  },

  /**
   * 输入评论内容 (Discover)
   */
  onCommentInput: function (e) {
     if (this.data.entryFrom !== 'discover') return;
     this.setData({ commentText: e.detail.value });
  },

  /**
   * 提交评论 (Discover)
   */
  submitComment: function () {
    if (this.data.entryFrom !== 'discover') return;

    const { dishId, commentText, kitchenId } = this.data;
    if (!commentText.trim()) { /* 提示 */ wx.showToast({ title: '请输入评论内容', icon: 'none' }); return; }
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) { /* 提示 */ wx.showToast({ title: '请先登录', icon: 'none' }); return; }

    this.setData({ submitting: true });

    discoverService.addComment(dishId, commentText, kitchenId).then(comment => {
      if (comment) {
        // ... (补充用户信息, 更新 comments, 清空输入, 更新 commentCount - 逻辑保持不变) ...
         const currentUserInfo = wx.getStorageSync('userInfo') || {};
         comment.userInfo = { nickName: currentUserInfo.nickName || '匿名用户', avatarUrl: currentUserInfo.avatarUrl || '/imgs/default-avatar.png' };
         // comment.createTimeFormatted = util.formatTime(...) // 格式化时间
         const newComments = [comment, ...this.data.comments];
         this.setData({
           comments: newComments, commentText: '', showCommentInput: false, submitting: false,
           'dish.commentCount': (this.data.dish.commentCount || 0) + 1
         });
         wx.showToast({ title: '评论成功', icon: 'success' });
      } else {
        this.setData({ submitting: false });
        wx.showToast({ title: '评论失败', icon: 'none' });
      }
    }).catch(err => {
      console.error('提交评论失败:', err);
      this.setData({ submitting: false });
      wx.showToast({ title: '评论失败，请重试', icon: 'none' });
    });
  },

  /**
   * 加载评论 (Discover)
   */
  loadComments: function (dishId = this.data.dishId, loadMore = false) {
    if (this.data.entryFrom !== 'discover' || !dishId) return; // 仅 Discover 模式加载
    if (this.data.commentsLoading || (loadMore && !this.data.hasMoreComments)) return;

    const { commentPageSize } = this.data;
    const currentPage = loadMore ? this.data.currentCommentPage : 0;
    this.setData({ commentsLoading: true });

    discoverService.getComments(dishId, commentPageSize, currentPage * commentPageSize)
      .then(comments => {
        // ... (处理返回的 comments, 补充 userInfo, 更新 comments, hasMoreComments, currentCommentPage - 逻辑保持不变) ...
         console.log(`加载评论结果 (Discover page: ${currentPage}):`, comments);
         const commentsWithUserInfo = comments.map(c => ({
           ...c,
           // createTimeFormatted: util.formatTime(new Date(c.createTime)), // 格式化时间
           userInfo: c.userInfo || { nickName: '用户', avatarUrl: '/imgs/default-avatar.png' }
         }));
         const newComments = currentPage === 0 ? commentsWithUserInfo : [...this.data.comments, ...commentsWithUserInfo];
         this.setData({
           comments: newComments, hasMoreComments: comments.length === commentPageSize,
           currentCommentPage: currentPage + 1, commentsLoading: false
         });
      })
      .catch(err => {
        console.error('加载评论失败 (Discover)', err);
        this.setData({ commentsLoading: false });
      });
  },

  // =============================================
  // == Default (Kitchen/Edit) 模式数据加载与方法 ==
  // =============================================

   /**
   * 加载数据 (Kitchen/Edit 入口)
   */
  loadDataForKitchen(kitchenId, dishId, forEdit = false) {
    console.log('加载数据 (Kitchen/Edit):', { kitchenId, dishId, forEdit });
    this.setData({ loading: true });

    Promise.all([
      kitchenService.getKitchenById(kitchenId),
      kitchenService.getDishById(kitchenId, dishId) // 使用 kitchenService 获取菜品
    ]).then(([kitchen, dish]) => {
      console.log('加载结果 (Kitchen/Edit):', { kitchen, dish });
      if (!kitchen || !dish) {
        // ... 错误处理 ...
        console.error('厨房或菜品不存在 (Kitchen/Edit)');
        wx.showToast({ title: '信息不存在', icon: 'none' });
        this.setData({ loading: false });
        setTimeout(() => wx.navigateBack(), 1500);
        return;
      }

      // Default 模式下，isFavorite 直接用 dish 对象的字段
      this.setData({
        kitchen,
        dish, // kitchenService 返回的 dish 应该包含 isFavorite 字段
        loading: false
        // isFavorite: dish.isFavorite || false // 直接使用 dish.isFavorite
      });

      // 编辑模式下可能需要进一步处理 dish 数据，例如初始化 ingredients, steps, tips
      if (forEdit) {
          this.setData({
             'dish.ingredients': dish.ingredients || [],
             'dish.steps': dish.steps || [],
             'dish.tips': dish.tips || [],
          });
      }


    }).catch(err => {
      console.error('加载 Kitchen/Edit 菜品详情失败', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({ loading: false });
    });
  },

  /**
   * 切换收藏状态 (Kitchen/Edit, 操作 mydishes.isFavorite)
   */
  toggleFavoriteForKitchen() {
     // 注意：这个函数是操作 mydishes 表中的 isFavorite 字段的示例
     // 你需要根据 kitchenService 或直接 DB 操作来实现
    const { dish } = this.data;
    if (!dish || !dish._id) return;

    const dishId = dish._id;
    const currentIsFavorite = dish.isFavorite || false; // 从 dish 对象获取
    const newFavoriteStatus = !currentIsFavorite;

    // --- 这里需要调用 kitchenService 更新菜品收藏状态，或直接操作数据库 ---
    // 示例：直接操作数据库 (假设用户有权限更新)
    db.collection('mydishes').doc(dishId).update({
      data: {
        isFavorite: newFavoriteStatus
      }
    }).then(() => {
      // 更新本地数据状态
      this.setData({
        'dish.isFavorite': newFavoriteStatus
      });
      wx.showToast({ title: newFavoriteStatus ? '已收藏' : '已取消收藏', icon: 'success' });
    }).catch(err => {
      console.error('更新收藏状态失败 (Kitchen)：', err);
      wx.showToast({ title: '操作失败', icon: 'error' });
    });
     // --- 更新结束 ---

     // 注意：Kitchen 模式下的收藏可能也需要更新本地缓存 wx.getStorageSync('favorites')
     // 这取决于你的收藏逻辑是基于 mydishes.isFavorite 还是单独的 favorites 缓存/表
  },

  /**
   * 添加到购物车 (Default - Kitchen 查看模式)
   */
  addToCart() {
    if (this.data.entryFrom === 'discover' || this.data.isEditMode) return; // 仅 Kitchen 查看模式有效

    const { kitchenId, dish } = this.data;
    if (!dish) { /* 提示 */ wx.showToast({ title: '菜品信息加载中', icon: 'none' }); return; }
    if (!kitchenId) { /* 提示 */ wx.showToast({ title: '厨房信息缺失', icon: 'none' }); return; } // Kitchen 模式必须有 kitchenId

    // ... (获取 cart, 查找 existingItem, 更新/添加, 保存 cart - 逻辑保持不变) ...
     let cart = wx.getStorageSync('cart') || [];
     const existingItem = cart.find(item => item.dishId === dish._id && item.kitchenId === kitchenId); // 必须匹配 kitchenId
     if (existingItem) {
       existingItem.quantity += 1;
     } else {
       cart.push({
         kitchenId: kitchenId, dishId: dish._id, name: dish.name, image: dish.image,
         price: dish.price || 0, quantity: 1, timestamp: new Date().getTime()
       });
     }
     wx.setStorageSync('cart', cart);
     wx.showToast({ title: '已加入购物车', icon: 'success' });
  },

  // =============================================
  // == 公共方法与编辑模式方法 ==
  // =============================================

  /**
   * 统一的切换收藏状态入口
   */
  toggleFavorite() {
      if (this.data.entryFrom === 'discover') {
          this.toggleFavoriteForDiscover();
      } else if (!this.data.isEditMode) { // 非编辑模式下的 Kitchen 视图
          this.toggleFavoriteForKitchen();
      }
      // 编辑模式下通常不显示收藏按钮
  },

  /**
   * 显示分享选项
   */
  showShareOptions() {
    this.setData({ showShareModal: true });
  },

  /**
   * 隐藏分享选项
   */
  hideShareOptions() {
    this.setData({ showShareModal: false });
  },

  /**
   * 页面上拉触底事件 - 加载更多评论 (仅 Discover)
   */
  onReachBottom: function () {
    if (this.data.entryFrom === 'discover') {
      console.log('页面触底 (Discover)，尝试加载更多评论');
      this.loadComments(this.data.dishId, true);
    }
  },

  /**
   * 输入处理 (Edit)
   */
  onInput(e) {
    if (!this.data.isEditMode) return;
    // ... (处理 field, value, 更新 dish - 逻辑保持不变) ...
     const { field } = e.currentTarget.dataset;
     const value = e.detail.value;
     if (field.includes('.')) {
       const keys = field.split('.');
       this.setData({ [`dish.${keys[0]}.${keys[1]}`]: value });
     } else {
       this.setData({ [`dish.${field}`]: value });
     }
  },

  /**
   * 设置难度 (Edit)
   */
  setDifficulty(e) {
    if (!this.data.isEditMode) return;
    this.setData({ 'dish.difficulty': e.detail.value });
  },

   // ... (其他编辑相关方法，如 addIngredient, removeIngredient, addStep, removeStep, chooseImage 等)


  /**
   * 保存菜品 (Edit) - 需要用 kitchenService.addDish 或 kitchenService.updateDish
   */
  saveDish() {
    if (!this.data.isEditMode) return;

    const { dish, kitchenId, dishId } = this.data; // dishId 在编辑现有菜品时存在

    // --- 表单验证 ---
    if (!dish.name) { wx.showToast({ title: '请输入菜品名称', icon: 'none' }); return; }
    // ... 其他验证 ...

    wx.showLoading({ title: '保存中...' });

    // --- 调用 kitchenService 保存 ---
    const savePromise = dishId
      ? kitchenService.updateDish(kitchenId, dishId, dish) // 更新
      : kitchenService.addDish(kitchenId, dish); // 新增

    savePromise.then((savedDishIdOrResult) => {
      wx.hideLoading();
      wx.showToast({ title: '保存成功', icon: 'success' });
      // 保存成功后通常返回上一页或跳转到详情页
      // 返回上一页并可能需要刷新列表
       const pages = getCurrentPages();
       const prevPage = pages[pages.length - 2]; // 获取上一个页面
       if (prevPage && typeof prevPage.loadData === 'function') {
         prevPage.loadData(); // 调用上一个页面的加载数据方法刷新
       }
       wx.navigateBack();

    }).catch(err => {
      wx.hideLoading();
      console.error('保存菜品失败:', err);
      wx.showToast({ title: '保存失败，请重试', icon: 'error' });
    });
  }
}) 